<template>
  <PageWrapper>
    <n-card :bordered="false" class="mb-3 proCard">
      <n-space align="center">
        <n-input-group style="width: 980px">
          <div style="margin-left: 10px !important;display: flex;align-items: center;">
            <n-input
              style="width: 100%;margin-left: 20px;"
              v-model:value="params.name"
              clearable
              placeholder="请输入充电盒名称"
              @keyup.enter="reloadTable"
            />
            <n-input
              style="width: 100%;margin-left: 20px;"
              v-model:value="params.charger_number"
              clearable
              placeholder="请输入充电盒编号"
              @keyup.enter="reloadTable"
            />
            <n-input
              style="width: 100%;margin-left: 20px;"
              v-model:value="params.charger_agents_name"
              clearable
              placeholder="请输入代理商名称"
              @keyup.enter="reloadTable"
            />
            <n-input
              style="width: 100%;margin-left: 20px;"
              v-model:value="params.charger_yuangong_name"
              clearable
              placeholder="请输入员工名称"
              @keyup.enter="reloadTable"
            />
            <n-input
              style="width: 100%;margin-left: 20px;"
              v-model:value="params.charger_bussiness_name"
              clearable
              placeholder="请输入商户名称"
              @keyup.enter="reloadTable"
            />
          </div>
          <n-button type="primary" style="margin-left: 40px !important;" @click="reloadTable">
            <template #icon>
              <n-icon>
                <SearchOutlined />
              </n-icon>
            </template>
            查询
          </n-button>
        </n-input-group>
      </n-space>
    </n-card>
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="basicTableRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        virtual-scroll
      >
        <template #tableTitle>
          <n-space align="center">
            <n-button type="primary" @click="openCreateDrawer">
              <template #icon>
                <n-icon>
                  <FileAddOutlined />
                </n-icon>
              </template>
              添加
            </n-button>
            <n-button type="primary" @click="importHandle">
              <template #icon>
                <n-icon>
                  <FileAddOutlined />
                </n-icon>
              </template>
              导入
            </n-button>
            <n-button type="primary" @click="batchAllocationHandle">
              <template #icon>
                <n-icon>
                  <FileAddOutlined />
                </n-icon>
              </template>
              批量分配
            </n-button>
          </n-space>
        </template>
      </BasicTable>
    </n-card>

    <!-- 导入文件 -->
    <n-modal v-model:show="modalShow">
      <n-card
        style="width: 600px"
        title="上传文件"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
          <!-- 上传文件： -->
          <div><n-button strong secondary type="info" @click="downmo">下载模板</n-button> </div>
          <div style="color: red;margin-top: 10px;margin-bottom: 10px;">操作后无数据请查看是否有此二维码或二维码已被绑定</div>
          <n-upload
            :action="`${uploadUrl1}/api/excel/importdeviceupdate`"
            @finish="handleFinish"
            name='file'
          >
            <n-button>上传文件</n-button>
          </n-upload>
      </n-card>
    </n-modal>

    <n-modal v-model:show="showModal">
      <n-spin :show="aShow">
        <n-card
          style="width: 1000px"
          title="商品管理"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <n-button strong secondary type="primary" @click="xuanzeGoods">选择商品</n-button>
          <n-table :single-line="false" style="margin-top: 10px;">
            <thead>
              <tr>
                <th>商品名称</th>
                <th>商品图片</th>
                <th>成本价</th>
                <th>售价</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in goodsList" :key="index">
                <td>{{ item.name }}</td>
                <td><img :src="item.sitepicture" width="60" height="60" /></td>
                <td>{{ item.costprice }}</td>
                <td>{{ item.danjia }}</td>
                <td> 
                  <n-button strong secondary type="primary" @click="goodsEdit(item)">编辑</n-button>
                  <n-button strong secondary type="error" style="margin-left: 10px;" @click="delGoods(item)">删除</n-button>
                </td>
              </tr>
            </tbody>
          </n-table>
        </n-card>
      </n-spin>
    </n-modal>

    <n-modal v-model:show="showBatchModal">
      <n-card
        style="width: 1000px"
        title="批量分配"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <n-form
          :model="formParams1"
          :rules="rules1"
          ref="formRef"
          label-placement="left"
          :label-width="100"
        >
          <n-form-item label="充电盒名称：" path="charger_number">
            {{rowKeysName}}
          </n-form-item>

          <n-form-item label="归属代理商：">
            <n-input placeholder="请选择归属代理商" disabled v-model:value="formParams1.charger_agents_name" />
            <n-button type="primary" @click="handleAgent" ghost>
              选择代理商
            </n-button>
          </n-form-item>

          <n-form-item label="归属商户">
            <n-input placeholder="请选择归属商户" disabled v-model:value="formParams1.charger_bussiness_name" />
            <n-button type="primary" @click="handleBusinesses" ghost>
              选择商户
            </n-button>
          </n-form-item>

          <n-form-item label="所属门店：">
            <n-input placeholder="请选择所属门店" disabled v-model:value="formParams1.charger_station_name" />
            <n-button type="primary" @click="handleStation" ghost>
              选择所属门店
            </n-button>
          </n-form-item>
          
        </n-form>

        <template #footer>
        <n-space>
          <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
        </n-space>
      </template>
      </n-card>
    </n-modal>

    <n-modal v-model:show="showModalagent">
        <n-card
          style="width: 600px"
          title="选择代理商"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <div style="display: flex;align-items: center;">
                <div style="width: 50px;">名称：</div>
                  <n-input
                    style="width: 50%;"
                    v-model:value="chargerParams.name"
                    clearable
                    placeholder="请输入名称"
                  />
                  <n-button style="margin-left: 10px" @click="chaSearchBut">搜索</n-button>
            </div>
          <n-table :bordered="false" :single-line="false">
            <thead>
            <tr>
              <th>代理商名称</th>
              <th>代理商账号</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item,index) in agentAll" :key="index">
              <td>{{item.nickname}}</td>
              <td>{{item.username}}</td>
              <td><n-button type="primary" @click="selectAgent(item)">选择</n-button></td>
            </tr>
          </tbody>
          </n-table>
          <n-pagination
              v-model:page="chargerParams.page"
              v-model:page-size="chargerParams.pageSize"
              :page-count="chargerParams.totalPage"
              show-size-picker
              :page-sizes="[10, 20, 30, 40]"
              :on-update-page="chargerChangePage"
              :on-update-page-size="chargerChangePagesize"
            />
        </n-card>
      </n-modal>

      <n-modal v-model:show="showStationModal">
        <n-card
          style="width: 600px"
          title="选择门店"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <div style="display: flex;align-items: center;">
                <div style="width: 50px;">名称：</div>
                  <n-input
                    style="width: 50%;"
                    v-model:value="stationAllParams.name"
                    clearable
                    placeholder="请输入名称"
                  />
                  <n-button style="margin-left: 10px" @click="stationAllList">搜索</n-button>
            </div>
          <div v-if="stationAll.length==0">
            该用户下没有门店请去添加门店
          </div>

          <n-table v-else :bordered="false" :single-line="false">
            <thead>
            <tr>
              <th>门店名称</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item,index) in stationAll" :key="index">
              <td>{{item.name}}</td>
              <td><n-button type="primary" @click="selectStation(item)">选择</n-button></td>
            </tr>
          </tbody>
          </n-table>
          <n-pagination
              v-model:page="stationAllParams.page"
              v-model:page-size="stationAllParams.pageSize"
              :page-count="stationAllParams.totalPage"
              show-size-picker
              :page-sizes="[10, 20, 30, 40]"
              :on-update-page="stationAllChangePage"
              :on-update-page-size="stationAllChangePagesize"
            />
        </n-card>
      </n-modal>

      <n-modal v-model:show="businessesModal">
        <n-card
          style="width: 600px"
          title="选择商户"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <div style="display: flex;align-items: center;">
              <div style="width: 50px;">名称：</div>
                <n-input
                  style="width: 50%;"
                  v-model:value="stationParams.name"
                  clearable
                  placeholder="请输入名称"
                />
                <n-button style="margin-left: 10px" @click="staSearchBut">搜索</n-button>
          </div>
          <n-table :bordered="false" :single-line="false">
            <thead>
              <tr>
                <th>商户名称</th>
                <th>商户账号</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,index) in businessesAll" :key="index">
                <td>{{item.nickname}}</td>
                <td>{{item.username}}</td>
                <td><n-button type="primary" @click="selectBusinesses(item)">选择</n-button></td>
              </tr>
            </tbody>
          </n-table>
          <n-pagination
              v-model:page="stationParams.page"
              v-model:page-size="stationParams.pageSize"
              :page-count="stationParams.totalPage"
              show-size-picker
              :page-sizes="[10, 20, 30, 40]"
              :on-update-page="stationChangePage"
              :on-update-page-size="stationChangePagesize"
            />
        </n-card>
      </n-modal>

      <n-modal v-model:show="showModalgoods">
        <n-card
          style="width: 600px"
          title="选择商品"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
        >
          <div style="display: flex;align-items: center;">
                <div style="width: 50px;">名称：</div>
                  <n-input
                    style="width: 50%;"
                    v-model:value="goodsParams.search"
                    clearable
                    placeholder="请输入名称"
                  />
                  <n-button style="margin-left: 10px" @click="goodsSearchBut">搜索</n-button>
            </div>
          <n-table :bordered="false" :single-line="false">
            <thead>
            <tr>
              <th>商品名称</th>
              <th>图片</th>
              <th>售价</th>
              <th>成本价</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item,index) in goodsAll" :key="index">
              <td>{{item.name}}</td>
              <td><img :src="item.sitepicture" width="60" height="60" /></td>
              <td>{{item.danjia}}</td>
              <td>{{item.costprice}}</td>
              <td><n-button type="primary" @click="selectGoods(item)">选择</n-button></td>
            </tr>
          </tbody>
          </n-table>
        </n-card>
      </n-modal>

    <CreateDrawer
      ref="createDrawerRef"
      :title="drawerTitle"
      :roleList="roleData"
      @change="reloadTable"
    />

    <CreateDrawergoods
      ref="createDrawerRefgoods"
      :roleList="goodsData"
      @change="reloadTable"
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { h, reactive, ref, onMounted } from 'vue';
  import { useMessage, FormRules } from 'naive-ui';
  import { BasicColumn, BasicTable, TableAction } from '@/components/Table';
  import { chargerlist,batchCharger,bussinessCharger,getStationList1,goodsLists,getallgoodsList1,selectGoodsinfo,delGoodsinfo } from '@/api/device/charger';
  import { allagent1,getallagentList1 } from '@/api/system/user';
  import { FileAddOutlined, SearchOutlined } from '@vicons/antd';
  import CreateDrawer from './CreateDrawer.vue';
  import CreateDrawergoods from './CreateDrawergoods.vue';
  import { columns } from './columns';
  import type { UploadFileInfo } from 'naive-ui'
  import { useGlobSetting } from '@/hooks/setting';
  import { useRouter } from 'vue-router';
  import type { formParamsType } from './types';
  const router = useRouter();
  const globSetting = useGlobSetting();
  const { uploadUrl } = globSetting;
  const uploadUrl1 = g.development.BASEURL;

  const showModal = ref(false);
  const goodsList = ref([]);
  const message = useMessage();
  const basicTableRef = ref();
  const rowKeys = ref([]);
  const rowKeysName = ref([]);
  const rowkeysChargerName = ref([]);
  const tableData = ref();
  const createDrawerRef = ref();
  const drawerTitle = ref('添加充电盒');
  const roleData = ref([]);
  const modalShow = ref(false);
  const showBatchModal = ref(false);
  const goodsAll = ref([]);
  const showStationModal = ref(false);
  const showModalagent = ref(false);
  const showModalgoods = ref(false);
  const agentAll = ref([]);
  const stationAll = ref([]);
  const subLoading = ref(false);
  const formRef: any = ref(null);
  const businessesModal = ref(false);

  const createDrawerRefgoods = ref();
  const goodsData = ref([]);

  const defaultValueRef = () => ({
    ids: null,
    charger_agents_name: '',
    charger_agents_id: 0,
    charger_station_name: '',
    charger_station_id: 0,
    charger_bussiness_id: 0,
    charger_bussiness_name: ''
  });

  const formParams1 = ref<formParamsType>(defaultValueRef());

  const defaultValueRefgoods = () => ({
    charger_id: 0,
    goods_id: 0,
  });
  const formParamsgoods = ref<formParamsType>(defaultValueRefgoods());

  const rules1: FormRules = {
    username: {
      required: true,
      message: '登录账号不能为空',
      trigger: 'blur',
    },
    nickname: {
      required: true,
      message: '名称不能为空',
      trigger: 'blur',
    },
    roleIds: {
      required: true,
      message: '角色不能为空',
      trigger: 'change',
      type: 'number',
    },
    password: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
  };

  const params = reactive({
    name: '',
    charger_number: '',
    charger_agents_name: '',
    charger_yuangong_name: '',
    charger_bussiness_name: '',
    type: 2
  });

  const handleFinish = ({
    file,
    event
  }: {
    file: UploadFileInfo
    event?: ProgressEvent
  }) => {
    var returnJson = (event?.target as XMLHttpRequest).response;
    let All = JSON.parse(returnJson);

    message.success(All.message);
  }

  function downmo(){
    window.open(g.development.BASEURL + '/moban.xlsx','_self');
  }

  const aShow = ref(false);
  const businessesAll = ref([]);
  const chargerParams = ref({
    name:'',
    page:1,
    pageSize:10,
    totalPage:1,
    charger_agents_id:''
  });

  const stationParams = ref({
    name:'',
    page:1,
    pageSize:10,
    totalPage:1,
    charger_agents_id:''
  });

  const stationAllParams = ref({
    name: '',
    page: 1,
    pageSize: 10,
    totalPage: 1,
    charger_agents_id: 0,
    charger_bussiness_id: 0
  });

  const goodsParams = ref({
    search:'',
    charger_id: '',
    goods_id: '',
  });

  function handleBusinesses(){
    businessesModal.value = true;
  }

  //代理商搜索
  async function chaSearchBut(){
    var agentAll1 = await getallagentList1(chargerParams.value);
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;
  }

  //代理商分页
  async function chargerChangePage(e){

    //改变一下页数
    chargerParams.value.page = e;
    //重新请求一下接口
    var agentAll1 = await getallagentList1(chargerParams.value);
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;
  }

  async function chargerChangePagesize(e){
    //改变条数
    chargerParams.value.pageSize = e;

    var agentAll1 = await getallagentList1(chargerParams.value);
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;
  }

  //门店分页
  async function stationAllChangePage(e){
    //改变一下页数
    stationAllParams.value.page = e;
    stationAllList();
  }
  async function stationAllChangePagesize(e){
    //改变条数
    stationAllParams.value.pageSize = e;
    stationAllList();
  }

  //商家分页
  async function stationChangePage(e){
    //改变一下页数
    stationParams.value.page = e;
    //重新请求一下接口
    var result = await bussinessCharger(stationParams.value);
    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;
  }
  
  async function stationChangePagesize(e){
    //改变条数
    stationParams.value.pageSize = e;
    var result = await bussinessCharger(stationParams.value);
    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;
  }

  function selectBusinesses(item){
    //商户id
    formParams1.value.charger_bussiness_id = item.id;
    //商户名称
    formParams1.value.charger_bussiness_name = item.username;
    businessesModal.value = false;

    //门店搜索
    stationAllList();
  }

  //商家搜索
  async function staSearchBut(){
    var result = await bussinessCharger(stationParams.value);
    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;
  }

  //商品搜索
  async function goodsSearchBut(){
    var goodsAll1 = await getallgoodsList1(goodsParams.value);
    goodsAll.value = goodsAll1;
  }

  // 选中商品
  function selectGoods(item){
    goodsParams.value.goods_id = item.id;

    selectGoodsinfo({ charger_id: goodsParams.value.charger_id,goods_id: goodsParams.value.goods_id }).then((res)=>{
      message.success("操作成功");
      showModal.value = false;
      showModalgoods.value = false;
    });
  }

  // 删除商品
  function delGoods(item){
    let id = item.id;

    delGoodsinfo({ goodscharger_id: id }).then((res)=>{
      message.success("删除成功");
      showModal.value = false;
      showModalgoods.value = false;
    });
  }

  const actionColumn: BasicColumn = reactive({
    width: 170,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
      return h(TableAction as any, {
        actions: [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '商品管理',
            onClick: goodsHandle.bind(null, record),
          },
        ],
      });
    },
  });

  const loadDataTable = async (res) => {
    const result = await chargerlist({ ...params, ...res });
    tableData.value = result.list;
    return result;
  };

  //商品管理
  function goodsHandle(record: Recordable) {
    let id = record.id;
    formParamsgoods.value.charger_id = id;

    goodsLists({ charger_id: id }).then((res)=>{
      goodsList.value = res;

      showModal.value = true;
    });

    goodsParams.value.charger_id = id;//选择商品
  }

  //编辑商品信息
  function goodsEdit(item){
    const { openDrawer } = createDrawerRefgoods.value;
    openDrawer(item.id);
  }

  function selectStation(item){
    formParams1.value.charger_station_id = item.id;
    formParams1.value.charger_station_name = item.name;
    showStationModal.value = false;
  }

  async function selectAgent(item){
    //代理商id
    formParams1.value.charger_agents_id = item.id;
    //代理商名称
    formParams1.value.charger_agents_name = item.username;

    formParams1.value.charger_bussiness_id = 0;
    formParams1.value.charger_bussiness_name = '';

    stationParams.value.charger_agents_id = item.id;

    //查询商户
    var result = await bussinessCharger(stationParams.value);

    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;

    //门店搜索
    stationAllList();

    showModalagent.value = false;
  }

  async function stationAllList(){
    if( formParams1.value.charger_bussiness_id == 0 && formParams1.value.charger_agents_id == 0 ){
      message.error("请选择归属代理商或归属商户");
    }else{//查询一下归属代理商的值
      stationAllParams.value.charger_agents_id = formParams1.value.charger_agents_id;
      stationAllParams.value.charger_bussiness_id = formParams1.value.charger_bussiness_id;
      var all123 = await getStationList1(stationAllParams.value);

      stationAllParams.value.totalPage = all123.totalPage;

      stationAll.value = all123.list;
    }
  }

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {

        if(formParams1.value.ids.length==0){
          message.error('请选择分配的设备');
        }

        //分配设备
        var formParams = formParams1.value;
        formParams.ids = formParams1.value.ids.join(",");

        batchCharger(formParams).then((res) => {
            showBatchModal.value = false;
            message.success('分配成功');
        });
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  function handleStation(){
    showStationModal.value = true;
  }

  function handleAgent() {
    showModalagent.value = true;
  }

  function xuanzeGoods(){
    showModalgoods.value = true;

    getallgoodsList1({ charger_id: formParamsgoods.value.charger_id }).then((res)=>{
      goodsAll.value = res;
    });
  }

  //批量分配
  function batchAllocationHandle() {
    var allJson = [];

    var key = rowKeys.value;
    var keyname = rowKeysName.value;

    if(key.length==0){
      message.success("请选择批量分配的设备");
      return false;
    }
    formParams1.value.ids = key;

    showBatchModal.value = true;
  }

  function importHandle() {
    modalShow.value = true;
  }

  function onCheckedRow(keys) {
    rowKeys.value = keys;
    rowKeysName.value = tableData.value.filter((item) => {
        return keys.includes(item.id);
      })
      .map((item) => {
        return item.charger_name;
      })
      .join(',');
  }

  function reloadTable() {
    basicTableRef.value.reload();
  }

  function openCreateDrawer() {
    const { openDrawer } = createDrawerRef.value;
    openDrawer();
  }

  function handleEdit(record: Recordable) {
    drawerTitle.value = '编辑充电盒';
    const { openDrawer } = createDrawerRef.value;
    openDrawer(record.id);
  }

  onMounted(async () => {
    //查询一下所有的代理商
    var agentAll1 = await getallagentList1(chargerParams.value);
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;
  });
</script>

<style lang="less" scoped>

</style>
